package de.lulusoft.anothertorrent.gui.commands;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;

import de.lulusoft.anothertorrent.core.rtorrent.Torrent;
import de.lulusoft.anothertorrent.gui.exceptions.ExceptionHandler;

public class DownloadSetConnectionSeed implements IHandler {
	
	public static final String ID = "de.lulusoft.anothertorrent.gui.commands.DownloadSetConnectionSeed";
	
	public static final String P_CONNECTION_SEED = "P_CONNECTION_SEED";
	public static final String P_SEED = "seed";
	public static final String P_INITIAL_SEED = "initial_seed";

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		if (event.getTrigger() instanceof Torrent)
		{
			Torrent t = (Torrent)event.getTrigger();
			String val = event.getParameter(P_CONNECTION_SEED);
			try {
				// stop torrent if active and Send cmd to server
				if (t.getState() != 0)
				{
					t.getServer().getRTorrentManager().torrentStop(t.getHash());
					t.getServer().getRTorrentManager().torrentSetConnectionSeed(t.getHash(), val);
					t.getServer().getRTorrentManager().torrentStart(t.getHash());
				}
				else
					t.getServer().getRTorrentManager().torrentSetConnectionSeed(t.getHash(), val);
			} catch (Exception e) {
				ExceptionHandler.alert("Could not set torrent connection seed", e);
			}
			
			// Change local cached data to reflect the changes immediately
			t.setConnection_seed(val);
		}
		return null;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public boolean isHandled() {
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
	}

}
